package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.model.DeviceShadowData;
import com.huaweicloud.sdk.iotda.v5.model.ProductSummary;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceResponse;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.huaweiyun.DeviceDto;
import com.zzyl.common.utils.huaweiyun.HuaweiIotUtil;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 智能设备基本信息Service业务层处理
 *
 * @author waker
 * @date 2025-09-16
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private HuaweiIotUtil huaweiIotUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询智能设备基本信息列表
     *
     * @param device 智能设备基本信息
     * @return 智能设备基本信息
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        // 1. 从物联网平台获取产品列表
        List<ProductSummary> productList = huaweiIotUtil.queryProductList();
        List<ProductVo> productVoList = BeanUtil.copyToList(productList, ProductVo.class);
        // 2. 存入redis
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, productVoList);
    }

    /**
     * 获取所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> getAllProduct() {
        // 1. 从redis获取产品列表
        List<ProductVo> productVoList = (List<ProductVo>) redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        // 2. 封装成list返回
        if (ObjectUtil.isNotEmpty(productVoList)) {
            return productVoList;
        }
        return Collections.emptyList();
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    @Override
    public void register(DeviceDto dto) {
        if (ObjectUtil.isEmpty(dto.getPhysicalLocationType())) {
            dto.setPhysicalLocationType(3);
        }
        // 1. 前置校验 判断设备名称何设备标识码是否重复 同一位置是否绑定了相同设备
        validateRegisterBefore(dto);
        // 2. 保存到华为云Iot平台
        String secret = IdUtil.simpleUUID();
        dto.setSecret(secret);
        String iotId = huaweiIotUtil.addDevice(dto);
        // 3. 保存到数据库
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setIotId(iotId);
        device.setSecret(secret);
        try {
            boolean result = this.save(device);
            if (!result) {
                // 如果保存数据库失败，调用华为删除设备
                this.huaweiIotUtil.removeDevice(iotId);
                throw new BaseException("注册设备失败");
            }
        } catch (Exception e) {
            // 如果保存数据库失败，调用华为删除设备
            this.huaweiIotUtil.removeDevice(iotId);
            throw new BaseException("注册设备失败");
        }
    }

    /**
     * 注册前置校验
     *
     * @param dto
     */
    private void validateRegisterBefore(DeviceDto dto) {
        // 1.判断设备名称何是否重复
        Long count = lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if (count > 0) {
            throw new BaseException("设备名称重复,请重新输入");
        }
        // 2.判断设备标识码是否重复
        count = lambdaQuery().eq(Device::getNodeId, dto.getNodeId()).count();
        if (count > 0) {
            throw new BaseException("设备标识码重复,请重新输入");
        }
        // 3.判断同一位置是否绑定了相同设备
        count = lambdaQuery().eq(Device::getLocationType, dto.getLocationType()).eq(Device::getProductKey, dto.getProductKey()).eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType()).eq(Device::getBindingLocation, dto.getBindingLocation()).count();
        if (count > 0) {
            throw new BaseException("同一位置已绑定相同设备,请重新选择");
        }
    }

    /**
     * 查询设备详细数据
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getDeviceDetail(String iotId) {
        // 1. 查询数据库设备详细数据
        Device device = lambdaQuery().eq(Device::getIotId, iotId).one();
        DeviceDetailVo deviceDetailVo = new DeviceDetailVo();
        if (ObjectUtil.isNotEmpty(device)) {
            BeanUtil.copyProperties(device, deviceDetailVo);
        }
        // 2. 查询华为云设备详细数据
        ShowDeviceResponse showDeviceResponse = huaweiIotUtil.queryDeviceDetail(iotId);
        deviceDetailVo.setDeviceStatus(showDeviceResponse.getStatus());
        // 时间字符串转换成LocalDateTime
        String activeTimeStr = showDeviceResponse.getActiveTime();
        if (ObjectUtil.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            // a.转换为上海时区
            deviceDetailVo.setActiveTime(activeTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime());
            // b. 直接加8小时
//            deviceDetailVo.setActiveTime(activeTime.plusHours(8));
        }
        // 3. 合并 返回数据
        return deviceDetailVo;
    }

    /**
     * 查询设备上报的数据
     *
     * @param iotId
     * @return
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        // 1. 向华为云IOT查询设备上报数据
        List<DeviceShadowData> shadow = huaweiIotUtil.queryDeviceShadowData(iotId);
        if (CollUtil.isEmpty(shadow)) {
            List<Object> emptyList = Collections.emptyList();
            return AjaxResult.success(emptyList);
        }
        // 2. 解析时间
        List<Map<String, Object>> list = new ArrayList<>();
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        //处理上报时间日期
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC)).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();

        jsonObject.forEach((k, v) -> {
            if (k.contains("Time")) {
                v = LocalDateTimeUtil.format(LocalDateTime.parse(v.toString(), DateTimeFormatter.ISO_DATE_TIME), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", k);
            map.put("value", v);
            map.put("eventTime", eventTime);
            list.add(map);
        });
        // 3. 封装成list返回
        return AjaxResult.success(list);
    }

    /**
     * 修改设备信息
     *
     * @param dto
     */
    @Override
    public void updateDevice(DeviceDto dto) {
        Device device = lambdaQuery().eq(Device::getId, dto.getId()).one();
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在!");
        }
        // 1. 修改华为云设备信息
        huaweiIotUtil.updateDeviceInfo(dto.getIotId(), dto.getDeviceName());
        // 2. 修改数据库设备信息
        BeanUtil.copyProperties(dto, device);
        lambdaUpdate().eq(Device::getId, device.getId()).update(device);
    }

    /**
     * 删除设备
     *
     * @param iotId
     */
    @Override
    @Transactional
    public void removeDevice(String iotId) {
        // 1. 删除数据库设备信息
        lambdaUpdate().eq(Device::getIotId, iotId).remove();
        // 2. 删除华为云设备信息
        huaweiIotUtil.removeDevice(iotId);
    }
}
